package com.randev.snapservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.randev.snapconfig.Config;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

public class ImageCounterService extends IntentService{
	int RESULT = 0;
	String key = "";
	private final String TAG ="ImageCounterService";
	
	public ImageCounterService() {
		super("ImageCounterService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Bundle extras = intent.getExtras();
		Log.w("ImageCount Service Started", getClass().getSimpleName() + "");
		
		if (extras != null) {
			Messenger progressMessenger = (Messenger) extras.get("IMAGECOUNTERPROGRESS");
			Message progressMessage = Message.obtain();
			progressMessage.arg1 = 1;
			try {
				progressMessenger.send(progressMessage);
			} catch (android.os.RemoteException e1) {
				Log.w(TAG, "Exception sending progress message", e1);
			}
			
		}
		
		getDataFromPreviousActivity(intent);
		String response = getImageCountWithKey(key);
		
		
		if (response.contentEquals("")) {
			RESULT = -1;
		} else {
			RESULT = 1;
		}
		
		
		
		if (extras != null) {
			Messenger messenger = (Messenger) extras.get("IMAGECOUNTMESSENGER");
			Message msg = Message.obtain();
			Bundle resultBundle = new Bundle();
			resultBundle.putString("Result", String.valueOf(RESULT));
			resultBundle.putString("Response", response);
			msg.setData(resultBundle);
			try {
				messenger.send(msg);
			} catch (android.os.RemoteException e1) {
				Log.w(TAG, "Exception sending message", e1);
			}
		}
		
		if (extras != null) {
			Messenger progressMessenger = (Messenger) extras.get("IMAGECOUNTERPROGRESS");
			Message progressMessage = Message.obtain();
			progressMessage.arg1 = 2;
			try {
				progressMessenger.send(progressMessage);
			} catch (android.os.RemoteException e1) {
				Log.w(TAG, "Exception sending progress message", e1);
			}
			
		}
	}
	
	private void getDataFromPreviousActivity(Intent intent) {
		try {
			Bundle extras = intent.getExtras();
			key = extras.getString("Key");
		}catch (Exception e) {
			Log.w(TAG, "Unable to get data from previous activity: " + e.toString());
		}
		
	}

	private String getImageCountWithKey(String key) {
		HttpClient httpClient = new DefaultHttpClient();
		String imageCountGetUrl = Config.IMAGE_COUNT_GET;
		HttpGet getImageCount = new HttpGet(imageCountGetUrl+key);
		StringBuilder stringBuilder = new StringBuilder();
		String imageCount = "";
		try {
			HttpResponse imageCountResponse = httpClient.execute(getImageCount);
			StatusLine statusLine = imageCountResponse.getStatusLine();
			int resultCode = statusLine.getStatusCode();
			
			if (resultCode == 200) {
				HttpEntity entity = imageCountResponse.getEntity();
		        InputStream content = entity.getContent();
		        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		        String line;
		        
		        
		        while ((line = reader.readLine()) != null) {
		        	stringBuilder.append(line);
		        }
			} else {
				Log.w("Result code : ", String.valueOf(resultCode));
			}
			
			imageCount = stringBuilder.toString();
			
		} catch (ClientProtocolException e) {
			Log.w(TAG, "Error getting image count+ " + e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			Log.w(TAG, "Error getting image count+ " + e.toString());
		}
		return imageCount;
	}

}
